<template>
  <div>
    <h1>商家列表</h1>
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input
          v-model="form.keyWord"
          placeholder="商品名称/SPU/品牌名称/商品id"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getProd()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="showprod">添加商品</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="ID" width="50" />
      <el-table-column prop="prodSpu" label="SPU" width="60" />
      <el-table-column prop="kindName" label="种类" />
      <el-table-column prop="typeName" label="分类" />
      <el-table-column prop="prodName" label="名称" />
      <el-table-column prop="brandName" label="品牌" />
      <el-table-column prop="unitName" label="单位" />
      <el-table-column prop="tagName" label="标签" />
      <el-table-column prop="prodStatus" label="状态">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.prodStatus == 1">上架</el-tag>
          <el-tag type="danger" v-if="scope.row.prodStatus == 0">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="appr" label="供应商" />
      <el-table-column prop="prodImage" label="封面">
        <template #default="scope">
          <el-image
            v-if="scope.row.prodImage != null"
            style="width: 50px; height: 50px"
            :src="scope.row.prodImage"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="300px">
        <template #default="scope">
          <el-button type="primary" size="small" @click="shopatta(scope.row)"
            >商品附件</el-button
          >
          <el-button type="success" size="small" @click="onprodInfo(scope.row)"
            >商品明细</el-button
          >
          <el-button type="primary" size="small">审核</el-button>
          <el-button type="danger" size="small" @click="deleteprod(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="form.pageNum"
      v-model:page-size="form.pageSize"
      :page-sizes="[2, 3, 4, 5]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible2" title="添加商品附件" width="500">
      <el-form :model="formAtta">
        <el-form-item label="商品轮播图" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="http://127.0.0.1:10010/product/type/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品视频" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="videoList"
            class="upload-demo"
            action="http://127.0.0.1:10010/product/type/upload"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleVideoRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :headers="headers"
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                作用于商品详情页顶部轮播的视频介绍,最大限制20MB.
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="上架时间" :label-width="formLabelWidth">
          <el-radio-group v-model="formAtta.upFlag">
            <el-radio value="0">立即上架</el-radio>
            <el-radio value="1">定时上架</el-radio>
          </el-radio-group>
          <el-date-picker
            v-model="formAtta.upTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="上架定时时间"
            v-if="formAtta.upFlag == 1"
          />
        </el-form-item>

        <el-form-item label="定时时间" :label-width="formLabelWidth">
          <el-switch
            v-model="formAtta.downFlag"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="" :label-width="formLabelWidth">
          <el-date-picker
            v-model="formAtta.downTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="下架定时时间"
            v-if="formAtta.downFlag == 1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addatta"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
      <el-form :model="prodData" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="商品种类"
          :label-width="formLabelWidth"
          prop="prodKind"
        >
          <el-radio-group v-model="prodData.prodKind">
            <el-radio
              v-for="item in prodOptions"
              :key="item.dictId"
              :label="item.dictName"
              :value="item.dictId"
            ></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="商品分类"
          :label-width="formLabelWidth"
          prop="prodType"
        >
          <el-tree-select
            v-model="prodData.prodType"
            :data="typeData"
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="prodName"
        >
          <el-input v-model="prodData.prodName" autocomplete="off" />
        </el-form-item>

        <el-form-item
          label="商品品牌"
          :label-width="formLabelWidth"
          prop="brandId"
        >
          <el-select
            v-model="prodData.brandId"
            placeholder="请选择商品品牌"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in Brandoptions"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="商品单位"
          :label-width="formLabelWidth"
          prop="unitId"
        >
          <el-select
            v-model="prodData.unitId"
            placeholder="请选择商品单位"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in Utiloptions"
              :key="item.dictValue"
              :label="item.dictName"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="商品标签"
          :label-width="formLabelWidth"
          prop="tagId"
        >
          <el-select
            v-model="prodData.tagId"
            placeholder="请选择商品标签"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in Tagoptions"
              :key="item.dictValue"
              :label="item.dictName"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" :label-width="formLabelWidth" prop="appr">
          <el-input v-model="prodData.appr" autocomplete="off" />
        </el-form-item>

        <el-form-item
          label="商品缩略图"
          :label-width="formLabelWidth"
          prop="prodImage"
        >
          <el-upload
            class="avatar-uploader"
            :headers="headers"
            action="http://127.0.0.1:10010/product/type/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import {
  getProdList,
  getDictListByTypeId,
  getSelectTypeList,
  getBrandData,
  addProd,
  addProdAtta,
  deleteBatchProd,
  deleteByProdId,
} from "../api/api";
import type { ComponentSize } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { fa, ro } from "element-plus/es/locales.mjs";
import { useRouter } from "vue-router";
const router = useRouter();
// useRouter赋值路径
// useRoute获取路径数据
const tableData = ref([]);
const total = ref(0);
const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);
const dialogFormVisible = ref(false);
const dialogFormVisible2 = ref(false);
const formLabelWidth = "140px";
const prodOptions = ref([]);
const typeData = ref([]);
const Brandoptions = ref([]);
const Utiloptions = ref([]);
const Tagoptions = ref([]);
const imageUrl = ref("");
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const multipleSelection = ref<any[]>([]);
const ruleFormRef = ref<FormInstance>();
const form = ref({
  keyWord: "",
  pageNum: 1,
  pageSize: 2,
});
const prodData = ref({
  prodId: null,
  prodSpu: "",
  prodKind: null,
  prodType: null,
  prodName: "",
  brandId: null,
  prodStatus: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  unitId: null,
  tagId: null,
  appr: null,
  prodImage: null,
  kindName: "",
  typeName: "",
  brandName: "",
  unitName: "",
  tagName: "",
});
const formAtta = ref({
  attaId: null,
  attaImages: "",
  attaVideo: "",
  createBy: "",
  createTime: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
  updateBy: "",
  updateTime: "",
});
const onprodInfo = (row: any) => {
  router.push("/home/prodInfo/" + row.prodId);
};
const deleteprod = (row: any) => {
  prodData.value.prodId = row.prodId;

  ElMessageBox.confirm("你确定删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteByProdId(prodData.value.prodId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          getProd();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
const batchDelete = () => {
  let ids = [];
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请先选择商品");
    return;
  }
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });

  ElMessageBox.confirm("你确定删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchProd(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          getProd();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

const addatta = () => {
  debugger;
  let attaImagesList: any = [];
  fileList.value.forEach((item) => {
    attaImagesList.push(item.response.data);
  });
  formAtta.value.attaImages = JSON.stringify(attaImagesList);

  if (videoList.value.length <= 0) {
    ElMessage.error("请上传视频");
    return;
  }

  formAtta.value.attaVideo = videoList.value[0].response.data;

  addProdAtta(formAtta.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible2.value = false;
      getProd();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const handleVideoRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const fileList = ref<UploadUserFile[]>([]);

const videoList = ref<UploadUserFile[]>([]);

const shopatta = (row: any) => {
  dialogFormVisible2.value = true;
  formAtta.value.prodId = row.prodId;
  fileList.value = [];
  videoList.value = [];
  formAtta.value = {
    attaId: null,
    downTime: "",
    prodId: row.prodId,
    upTime: "",
  };
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      prodData.value.prodImage = imageUrl.value;
      addProd(prodData.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          getProd();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const checkAge = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请上传图片"));
  } else {
    return callback();
  }
};
const rules = ref<FormRules>({
  prodKind: [
    { required: true, message: "商品种类不能为空", trigger: "change" },
  ],
  prodType: [
    { required: true, message: "商品分类不能为空", trigger: "change" },
  ],
  prodName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  brandId: [{ required: true, message: "商品品牌不能为空", trigger: "change" }],
  unitId: [{ required: true, message: "商品单位不能为空", trigger: "change" }],
  tagId: [{ required: true, message: "商品标签不能为空", trigger: "change" }],
  appr: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
  prodImage: [{ validator: checkAge, trigger: "change" }],
});
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};
const getprodKind = () => {
  getDictListByTypeId(1).then((res) => {
    if (res.data.code == 200) {
      prodOptions.value = res.data.data;
    }
  });
};
const showprod = () => {
  prodData.value = {
    prodId: null,
    prodSpu: "",
    prodKind: null,
    prodType: null,
    prodName: "",
    brandId: null,
    prodStatus: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    unitId: null,
    tagId: null,
    appr: null,
    prodImage: null,
  };
  imageUrl.value = "";
  dialogFormVisible.value = true;
};
const getProd = () => {
  getProdList(form.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  form.value.pageSize = val;
  getProd();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  form.value.pageNum = val;
  getProd();
};
onMounted(() => {
  getProd();
  getprodKind();
  getSelectTypeList().then((res) => {
    if ((res.data.code = 200)) {
      typeData.value = res.data.data;
    }
  });
  getBrandData().then((res) => {
    if ((res.data.code = 200)) {
      Brandoptions.value = res.data.data;
    }
  });
  getDictListByTypeId(2).then((res) => {
    if (res.data.code == 200) {
      Utiloptions.value = res.data.data;
    }
  });
  getDictListByTypeId(3).then((res) => {
    if (res.data.code == 200) {
      Tagoptions.value = res.data.data;
    }
  });
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
